package com.xsz.service;

import com.xsz.entity.User;
import com.xsz.repository.UserRepository;
import com.xsz.util.KeyUtil;
import com.xsz.util.MD5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service

public class UserService {
	@Resource
    UserRepository userRepository;
	@Resource
	RedisTemplateService redisTemplateService;

	//新建
	public User add(User user) {
		user.setId(KeyUtil.getId());
		return userRepository.save(user);
	}
	
	//修改

	public User update(User user) {
		User puser = userRepository.save(user);
		redisTemplateService.set(user.getId()+"login",puser);
		return puser;
	}
	
	
	//删除

	public void delete(String id) {
		 userRepository.deleteById(id);
	}
	
	//查询

	public User selectById(String id) {
		User user = redisTemplateService.get(id+"login",User.class);
		if(user==null) {
			user=userRepository.findById(id).get();
			redisTemplateService.set(user.getId()+"login",user);
		}
		 return user;
	}
	

	public List<User> getAll() {
		return userRepository.findAll();
	}

	public User login(String name, String pwd) {
		User user=userRepository.findByNameAndPwd(name, pwd);
		return user;
	}

	public List<User> likeName(String name) {
		return userRepository.findByNameLike(name+"%");
	}

	public User getByName(String name) {
		return userRepository.findByName(name);
	}

	public User selectByIdAndPwd(User user) {
		String password = MD5Utils.encrypt(user.getName(), user.getPwd());
		user.setPwd(password);
		return userRepository.findByIdAndPwd(user.getId(),user.getPwd());
	}

	public void updatePwdById(User user) {
		String password = MD5Utils.encrypt(user.getName(), user.getPwd());
		user.setPwd(password);
		userRepository.updatePwdById(user.getPwd(),user.getId());
	}

	public void updateRoleById(String id) {
		int rsint=userRepository.updateRoledById(2,id);
		if(rsint>0) {
			User user = redisTemplateService.get(id+"login",User.class);
			user.setRole(2);
			redisTemplateService.set(user.getId()+"login",user);
		}
	}

}
